<template>
  <el-card shadow="always" class="h-full">
    <template #header>
      <span class="text-lg">设置</span>
    </template>

    <el-form label-width="100px" :inline="false" label-position="top">
      <el-form-item label="关键人员数据导入">
        <el-input v-model="db_path">
          <template #append>
            <el-button type="primary" size="default" @click="open">
              <FileExcel theme="outline" size="16" fill="#333" />
            </el-button>
          </template>
        </el-input>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { FileExcel } from '@icon-park/vue-next'
import useConfig from '@renderer/composables/useConfig'
import * as XLSX from 'xlsx'
import useKeyPerson from '@renderer/composables/useKeyPerson'
import useComp from '@renderer/composables/useComp'

const { readxls } = useConfig()
const { add: addKeyPerson } = useKeyPerson()
const { all: allComp, add: addComp, comps } = useComp()

const db_path = ref('')

const open = async () => {
  readxls(async (wb: XLSX.WorkBook) => {
    const sht = wb.Sheets['关键人员库']
    const row = XLSX.utils.sheet_to_json(sht)
    for await (const r of row) {
      await allComp()
      const {
        序号: id,
        工序: gongxu,
        分包商: compName,
        姓名: name,
        身份证: iCard,
        职务: zhiwu,
        备注: remark
      } = r
      // console.log({ id, gongxu, compName, name, iCard, zhiwu, remark })
      const comp = comps.value.find((c) => c.shortName === compName)
      // console.log(comp)
      const compId = comp
        ? comp.id
        : await addComp({
            name: compName,
            shortName: compName,
            fr: '--',
            sjfzr: '--'
          })
      // 将数据添加至数据库中
      addKeyPerson({
        gongxu,
        compId: compId!,
        name,
        iCard,
        zhiwu,
        remark
      })
    }
  })
}
</script>
